package com.example.camerapush.util;

import android.content.Context;
import android.graphics.Bitmap;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Author:lsh
 * Version: 1.0
 * Description:
 * Date: 2018/2/22
 */

public class FileUtils {
    //    public static final String FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "camerapush";
    public static String FILE_PATH;


    public static File saveFile(int handle, Bitmap bitmap,Context context) {
        FILE_PATH = context.getCacheDir().getAbsolutePath() + File.separator + "camerapush";
        File f = new File(FILE_PATH);
        if (!f.exists()) {
            f.mkdirs();
        }
        File file = new File(FILE_PATH, handle + ".JPG");
        try {
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
        } catch (Exception e) {
            return null;
        } finally {
            if (bitmap != null)
                bitmap.recycle();
        }

        return file;
    }

    public static void deleteFile(Context context,int handle) {
        FILE_PATH = context.getCacheDir().getAbsolutePath() + File.separator + "camerapush";
        File file = new File(FILE_PATH, handle + ".JPG");
        if (file.exists()) {
            file.delete();
        }
    }

    public static void clearCache(Context context) {
        FILE_PATH = context.getCacheDir().getAbsolutePath() + File.separator + "camerapush";
        deleteFilesByDirectory(new File(FILE_PATH));
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }
}
